package com.credit.web.basic;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.persistence.SearchDataTransform;
import com.credit.context.CreditServletContext;
import com.credit.entity.CreditCompanyLoan;
import com.credit.entity.CreditGrabOrder;
import com.credit.entity.CreditLiberalLoan;
import com.credit.entity.CreditLoanLog;
import com.credit.entity.CreditLoanOrder;
import com.credit.entity.CreditPersonalLoan;
import com.credit.entity.CreditProductInfo;
import com.credit.entity.CreditStudentLoan;
import com.credit.entity.CreditUserIdentify;
import com.credit.entity.CreditUserInfo;
import com.credit.entity.CreditWorkerLoan;
import com.credit.exception.ErrorException;
import com.credit.service.CreditGrabOrderService;
import com.credit.service.CreditLoanLogService;
import com.credit.service.CreditOrderService;
import com.credit.service.CreditProductService;
import com.credit.service.RedisService;
import com.credit.service.UserService;
import com.credit.util.AmountUtil;
import com.credit.util.BeanToMapUtil;
import com.credit.util.CalcuationOrderPriceUtil;
import com.credit.util.CodeValueUtil;
import com.credit.util.CoinUtil;
import com.credit.util.Constants;
import com.credit.util.DateFormatUtil;
import com.credit.util.LoanLogUtil;
import com.credit.util.ParamsConstant;
import com.credit.util.ParamsMapUtil;
import com.credit.util.PositionUtil;
import com.credit.util.RealNameUtil;
import com.credit.util.ReflectionUtil;
import com.credit.util.push.AndroidPush;
import com.credit.web.basic.bean.ResBean;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/creditOrder")
public class CreditOrderController {
	

	@Autowired
	private CreditOrderService creditOrderService;
	@Autowired
	private CreditLoanLogService creditLoanLogService;
	@Autowired
	private CreditGrabOrderService creditGrabOrderService;
	@Autowired
	private UserService userService;
	@Autowired
	private CreditProductService creditProductService;
	@Autowired
	private RedisService redisService;
	
	/**
	 * 获取信贷订单列表
	 * @param request
	 * @param response
	 * @param creditType
	 * @param pageNumber
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	@ResponseBody
	@RequestMapping(value = "/creditList", method = RequestMethod.POST)
	public void creditList(HttpServletRequest request, HttpServletResponse response,String city,
			/*@RequestParam("creditType") int creditType,*/@RequestParam(value = "page", defaultValue = "1") int pageNumber) throws IllegalArgumentException, IllegalAccessException{
		CreditUserInfo userInfo = CreditServletContext.getUserInfo();
		
		String workType = request.getParameter("workType");
		String mortgage = request.getParameter("mortgage");
		String creditRecord = request.getParameter("creditRecord");
		
		Map<String, Object> searchParams = new TreeMap<String, Object>();
/*		if(creditType!=CodeValueUtil.ALL_CODE){
			searchParams.put("EQ_creditType", creditType);
		}*/
		
		if(!StringUtils.isEmpty(workType)){
			searchParams.put("EQ_workType", workType);
		}
		
		if(!StringUtils.isEmpty(mortgage)){
			searchParams.put("EQ_mortgage", workType);
		}
		
		if(!StringUtils.isEmpty(creditRecord)){
			searchParams.put("EQ_creditRecord", workType);
		}
		
		//searchParams.put("IN_status",new Integer[]{CodeValueUtil.STATUS_TAKINGORDER,CodeValueUtil.STATUS_CANCELORDER,CodeValueUtil.STATUS_FINSHORDER});
		
		if(!StringUtils.isEmpty(city)){
			searchParams.put("EQ_currentCity", city);
		}
				
		Map<String, SearchDataTransform> dataTyps = new HashMap<String, SearchDataTransform>();
		

		Page<CreditLoanOrder> page = creditOrderService.getListPage(searchParams, pageNumber, ParamsConstant.PAGESIZE, "createTime", dataTyps);
		
		List<CreditLoanOrder> orderList = page.getContent();
		List<Map<String,Object>> orderListReturn = new ArrayList<Map<String,Object>>();
		for(CreditLoanOrder loanOrder:orderList){
			
			Map<String,Object> paramsMap = BeanToMapUtil.getMap(loanOrder);
			
			ParamsMapUtil.replace(paramsMap);
			
			Integer sharePrice = CalcuationOrderPriceUtil.calcuationPrice(loanOrder);
			paramsMap.put("relativeTime", DateFormatUtil.format(loanOrder.getCreateTime()));//展示相对时间
			paramsMap.put("workInfo", loanOrder.getCurrentCity()+" "+PositionUtil.getPosition(loanOrder)+PositionUtil.getStudentGrade(loanOrder));
			paramsMap.put("creditInfo",PositionUtil.getCreditInfo(loanOrder));
			paramsMap.put("sharePrice", sharePrice);//共享价格
			paramsMap.put("exclusivePrice", 2*sharePrice);//独享价格
			
			//身份证
			paramsMap.put("realName", RealNameUtil.getAppellation(loanOrder.getRealName(), loanOrder.getSex()));
			if(loanOrder.getProcessFlag().intValue()<CodeValueUtil.PROCESSFLAG_TAKING){
				paramsMap.put("IDNumber",!StringUtils.isEmpty(loanOrder.getIDNumber())?ParamsMapUtil.getIDNumber(loanOrder.getIDNumber()):"");
				paramsMap.put("mobile", "");
				//修改单位名称
				ParamsMapUtil.updateCompanyName(paramsMap);
			}else{
				CreditUserInfo user = userService.findUserById(loanOrder.getUserId());
				paramsMap.put("mobile", user.getMobile());
			}
			
			orderListReturn.add(paramsMap);
		}
		
		ResBean resBean = CreditServletContext.getResBean();
		resBean.getData().put("orderList", orderListReturn);
		CreditServletContext.setResBean(resBean);
	}
	
	/**
	 * 信贷订单进度查询
	 * @param request
	 * @param response
	 * @param loadId
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	@ResponseBody
	@RequestMapping(value = "/process", method = RequestMethod.POST)
	public void process(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("loanId") Long loanId) throws IllegalArgumentException, IllegalAccessException {
		CreditUserInfo userInfo = CreditServletContext.getUserInfo();
		
		List<CreditLoanLog> loanLogList = creditLoanLogService.findLoanLogByLoanIdAndUid(loanId,userInfo.getId(),ParamsConstant.appTypeMap.get(request.getHeader("appName")));
		List<Map<String,Object>> returnList = new ArrayList<Map<String,Object>>();
		for(CreditLoanLog loanLog:loanLogList){
			returnList.add(BeanToMapUtil.getMap(loanLog));
		}
		
		ResBean resBean = CreditServletContext.getResBean();
		resBean.getData().put("loanLogList", returnList);
		CreditServletContext.setResBean(resBean);
	}
	
	/**
	 * 我的客户列表
	 * @param request
	 * @param response
	 * @param pageNumber
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	@ResponseBody
	@RequestMapping(value = "/customerList", method = RequestMethod.POST)
	public void customerList(HttpServletRequest request, HttpServletResponse response,@RequestParam("orderType") String orderType,
			@RequestParam(value = "page",defaultValue = "1") int pageNumber) throws IllegalArgumentException, IllegalAccessException {
		CreditUserInfo userInfo = CreditServletContext.getUserInfo();
		
		Map<String, Object> searchParams = new TreeMap<String, Object>();
		searchParams.put("EQ_managerId", userInfo.getId());
		searchParams.put("EQ_orderType",orderType);
		
		Map<String, SearchDataTransform> dataTyps = new HashMap<String, SearchDataTransform>();
		

		Page<CreditGrabOrder> page = creditOrderService.getCustomerListPage(searchParams, pageNumber, ParamsConstant.PAGESIZE, "createTime", dataTyps);
		List<CreditGrabOrder> orderList = page.getContent();
		List<Map<String,Object>> customerListReturn = new ArrayList<Map<String,Object>>();
		for(CreditGrabOrder loadOrder:orderList){
			Map<String,Object> returnMap = BeanToMapUtil.getMap(loadOrder);
			ParamsMapUtil.replace(returnMap);
			customerListReturn.add(returnMap);
		}
		
		ResBean resBean = CreditServletContext.getResBean();
		resBean.getData().put("customerList", customerListReturn);
		CreditServletContext.setResBean(resBean);
	}
	
	/**
	 * 发单
	 * @param request
	 * @param response
	 * @param loadId
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws ErrorException 
	 */
	@ResponseBody
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public void create(HttpServletRequest request, HttpServletResponse response) throws IllegalArgumentException, IllegalAccessException, ErrorException {
		
		CreditUserInfo userInfo = CreditServletContext.getUserInfo();
		
		String realName = request.getParameter("realName");
		String sex = request.getParameter("sex");
		String age = request.getParameter("age");
		String amount = request.getParameter("amount");
		String deadline = request.getParameter("deadline");
		String homeCity = request.getParameter("homeCity");
		String currentCity = request.getParameter("currentCity");
		String productId = request.getParameter("productId");
		String workType = request.getParameter("workType");
		String creditCard = request.getParameter("creditCard");
		String creditRecord = request.getParameter("creditRecord");
		String creditLimit = request.getParameter("creditLimit");
		String capital = request.getParameter("capital");
		String mortgage = request.getParameter("mortgage");
		String debtType = request.getParameter("debtType");
		String insurance = request.getParameter("insurance");
		String insuranceLimit = request.getParameter("insuranceLimit");
		String highInterest = request.getParameter("highInterest");
		String education = request.getParameter("education");
		String purpose = request.getParameter("purpose");
		String mesasge = request.getParameter("mesasge");
		String IDNumber = request.getParameter("IDNumber");
		
		if(StringUtils.isEmpty(amount)){
			throw new ErrorException(Constants.AMOUNT_NOTNULL_ERROR_CODE, Constants.AMOUNT_NOTNULL_ERROR_DESC);
		}
		
		if(StringUtils.isEmpty(deadline)){
			throw new ErrorException(Constants.DEADLINE_NOTNULL_ERROR_CODE, Constants.DEADLINE_NOTNULL_ERROR_DESC);
		}
		
		if(StringUtils.isEmpty(realName)){
			throw new ErrorException(Constants.REALNAME_NOTNULL_ERROR_CODE, Constants.REALNAME_NOTNULL_ERROR_DESC);
		}
		
		if(StringUtils.isEmpty(age)){
			throw new ErrorException(Constants.AGE_NOTNULL_ERROR_CODE, Constants.AGE_NOTNULL_ERROR_DESC);
		}
		
		if(StringUtils.isEmpty(sex)){
			throw new ErrorException(Constants.SEX_NOTNULL_ERROR_CODE, Constants.SEX_NOTNULL_ERROR_DESC);
		}
		
		if(StringUtils.isEmpty(homeCity)){
			throw new ErrorException(Constants.HOMECITY_NOTNULL_ERROR_CODE, Constants.HOMECITY_NOTNULL_ERROR_DESC);
		}
		
		if(StringUtils.isEmpty(currentCity)){
			throw new ErrorException(Constants.HOMECITY_NOTNULL_ERROR_CODE, Constants.HOMECITY_NOTNULL_ERROR_DESC);
		}
		
		
		//校验稍后做
/*		if(!StringUtils.isEmpty(IDNumber)&&!IDNumber.matches(ParamsConstant.idcard_reg)){
			throw new ErrorException(Constants.IDCARD_VALIDATE_ERROR_CODE, Constants.IDCARD_VALIDATE_ERROR_DESC);
		}*/
		
		
		CreditLoanOrder loanOrder = new CreditLoanOrder();
		
		ReflectionUtil.setFieldValue(loanOrder, CreditServletContext.getScopeLocal());
		
		loanOrder.setUserId(userInfo.getId());
		CreditProductInfo productInfo = null;
		if(!StringUtils.isEmpty(productId)){
			loanOrder.setProductId(Long.valueOf(productId));
			loanOrder.setOrderType(CodeValueUtil.ORDERTYPE_EXCLUSIVE);
			productInfo = creditProductService.findProductById(loanOrder.getProductId());
			loanOrder.setCreditManager(productInfo.getUserId());
		}else{
			loanOrder.setOrderType(CodeValueUtil.ORDERTYPE_ORDINARY);
		}
		loanOrder.setProcessFlag(CodeValueUtil.PROCESSFLAG_SUBMIT);//提交成功
		loanOrder.setProcessStatus(1);//默认状态
		loanOrder.setStatus(CodeValueUtil.STATUS_TAKINGORDER);
		loanOrder.setTakingPeople(0);
		loanOrder.setCreateTime(new Date());
		loanOrder.setUpdateTime(new Date());
		loanOrder.setFlushTime(new Date());
		
		
		CreditLoanOrder returnLoadOrder = null;
		if(loanOrder.getWorkType().equals(CodeValueUtil.WORKTYPE_OFFICE)){//上班族贷款
			String companyName = request.getParameter("companyName");
			String companyType = request.getParameter("companyType");
			String incomeType = request.getParameter("incomeType");
			String openSalary = request.getParameter("openSalary");
			String cashIncome = request.getParameter("cashIncome");
			String socialInsurance = request.getParameter("socialInsurance");
			String socialBase = request.getParameter("socialBase");
			String socialYears = request.getParameter("socialYears");
			String housingFund = request.getParameter("housingFund");
			String fundsYears = request.getParameter("fundsYears");
			String fundsAmount = request.getParameter("fundsAmount");
			
			//校验稍后做
			
			CreditWorkerLoan workLoan = new CreditWorkerLoan();
			workLoan.setUserId(userInfo.getId());
			
			
			ReflectionUtil.setFieldValue(workLoan, CreditServletContext.getScopeLocal());
			
			
			Map<String,Object> map = BeanToMapUtil.getMap(workLoan);
			map.remove("loanId");
			
			loanOrder.setExtAttribute(JSONObject.fromObject(map).toString());
			
			returnLoadOrder = creditOrderService.create(loanOrder,workLoan);
			
		}else if(loanOrder.getWorkType().equals(CodeValueUtil.WORKTYPE_PERSONAL)){//网店/个体户贷款
			
			String licence = request.getParameter("licence");
			String annualFlow = request.getParameter("annualFlow");
			String operateYears = request.getParameter("operateYears");
			String address = request.getParameter("address");
			
			CreditPersonalLoan personalLoan = new CreditPersonalLoan();
			personalLoan.setUserId(userInfo.getId());
			
			ReflectionUtil.setFieldValue(personalLoan, CreditServletContext.getScopeLocal());
			
			Map<String,Object> map = BeanToMapUtil.getMap(personalLoan);
			map.remove("loanId");
			
			loanOrder.setExtAttribute(JSONObject.fromObject(map).toString());
			
			returnLoadOrder = creditOrderService.create(loanOrder,personalLoan);
			
		}else if(loanOrder.getWorkType().equals(CodeValueUtil.WORKTYPE_STUDENT)){//学生贷款
			
			String shcoolName = request.getParameter("shcoolName");
			String grade = request.getParameter("grade");
			String xuexinAccount = request.getParameter("xuexinAccount");
			
			CreditStudentLoan studentLoan = new CreditStudentLoan();
			studentLoan.setUserId(userInfo.getId());
			
			ReflectionUtil.setFieldValue(studentLoan, CreditServletContext.getScopeLocal());
			
			Map<String,Object> map = BeanToMapUtil.getMap(studentLoan);
			map.remove("loanId");
			
			loanOrder.setExtAttribute(JSONObject.fromObject(map).toString());
			
			returnLoadOrder = creditOrderService.create(loanOrder,studentLoan);
			
		}else if(loanOrder.getWorkType().equals(CodeValueUtil.WORKTYPE_LIBERAL)){//自由职业贷款
			String cashIncome = request.getParameter("cashIncome");
			
			CreditLiberalLoan liberalLoan = new CreditLiberalLoan();
			liberalLoan.setUserId(userInfo.getId());
			
			ReflectionUtil.setFieldValue(liberalLoan, CreditServletContext.getScopeLocal());
			
			
			Map<String,Object> map = BeanToMapUtil.getMap(liberalLoan);
			map.remove("loanId");
			
			loanOrder.setExtAttribute(JSONObject.fromObject(map).toString());
			
			returnLoadOrder = creditOrderService.create(loanOrder,liberalLoan);
			
		}else if(loanOrder.getWorkType().equals(CodeValueUtil.WORKTYPE_COMPANY)){//企业主贷款
			String licence = request.getParameter("licence");
			String annualFlow = request.getParameter("annualFlow");
			String operateYears = request.getParameter("operateYears");
			String address = request.getParameter("address");
			String companyName = request.getParameter("companyName");
			
			CreditCompanyLoan companyLoan = new CreditCompanyLoan();
			companyLoan.setUserId(userInfo.getId());
			
			ReflectionUtil.setFieldValue(companyLoan, CreditServletContext.getScopeLocal());
			
			
			Map<String,Object> map = BeanToMapUtil.getMap(companyLoan);
			map.remove("loanId");
			
			loanOrder.setExtAttribute(JSONObject.fromObject(map).toString());
			
			returnLoadOrder = creditOrderService.create(loanOrder,companyLoan);
			
		}
		
		List<Long> userInfoList = new ArrayList<Long>();
		
		//推送
		String title = StringUtils.isEmpty(productId)?"新贷款申请":productInfo.getProductName()+"贷款申请";
		String ticker = RealNameUtil.getAppellation(realName, Integer.valueOf(sex))+"，贷款额度"+amount+"元，"+PositionUtil.getPosition(returnLoadOrder)+PositionUtil.getCondition(returnLoadOrder);
		if(!StringUtils.isEmpty(productId)){ //指定经理推送
			userInfoList.add(userService.findUserById(returnLoadOrder.getCreditManager()).getId());
			
		}else{  //当前城市的经理推送
			userInfoList = userService.findUserByCurrentCity(currentCity);
		}
		
		List<Long> pushList = userInfoList;
		CreditLoanOrder loanOrderMessage = returnLoadOrder;
		final String pushTitle = title;
		new Thread(new Runnable(){

			@Override
			public void run() {
				
				if(pushList.size()>0){
					AndroidPush push = new AndroidPush();
					StringBuilder sb = new StringBuilder();
					if(pushList.size()>50){
						int i = 0;
						for(Long id:pushList){
							
							redisService.saveForZSet(ParamsConstant.CREDIT_ORDER_PUSH_MESSAGE, String.valueOf(id), loanOrderMessage.getId(), System.currentTimeMillis());
							
							if(i>=50){
								i = 0;
								try {
									push.sendAndroidCustomizedcast("2", sb.deleteCharAt(sb.length()-1).toString(), pushTitle, ticker, "有新的单子发布，请赶快去抢单。");
								    sb.delete(0, sb.length());
								} catch (Exception e) {
									e.printStackTrace();
								}

							}
							
							sb.append(id).append(",");
							i++;
						}
					}else{
						for(Long id:pushList){
							
							redisService.saveForZSet(ParamsConstant.CREDIT_ORDER_PUSH_MESSAGE, String.valueOf(id), loanOrderMessage.getId(), System.currentTimeMillis());
							
							sb.append(id).append(",");
						}
						try {
							push.sendAndroidCustomizedcast("2", sb.deleteCharAt(sb.length()-1).toString(), pushTitle, ticker, "有新的单子发布，请赶快去抢单。");
						} catch (Exception e) {
							
							e.printStackTrace();
						}
						
					}
				}
				
			}
			
		}).start();
		
        Integer people = userInfoList.size();
		
		ResBean resBean = CreditServletContext.getResBean();
		resBean.getData().put("people", people);
		CreditServletContext.setResBean(resBean);
	}
	
	
	/**
	 * 我的贷款列表
	 * @param request
	 * @param response
	 * @param pageNumber
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	@ResponseBody
	@RequestMapping(value = "/mylist", method = RequestMethod.POST)
	public void mylist(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "page", defaultValue = "1") int pageNumber) throws IllegalArgumentException, IllegalAccessException{
		CreditUserInfo userInfo = CreditServletContext.getUserInfo();
		
		Map<String, Object> searchParams = new TreeMap<String, Object>();
		searchParams.put("EQ_userId", userInfo.getId());
			
		Map<String, SearchDataTransform> dataTyps = new HashMap<String, SearchDataTransform>();
		

		Page<CreditLoanOrder> page = creditOrderService.getListPage(searchParams, pageNumber, ParamsConstant.PAGESIZE, "createTime", dataTyps);
		
		List<CreditLoanOrder> orderList = page.getContent();
		List<Map<String,Object>> orderListReturn = new ArrayList<Map<String,Object>>();
		for(CreditLoanOrder loadOrder:orderList){
			orderListReturn.add(ParamsMapUtil.replace(BeanToMapUtil.getMap(loadOrder)));
		}
		
		ResBean resBean = CreditServletContext.getResBean();
		resBean.getData().put("myList", orderListReturn);
		CreditServletContext.setResBean(resBean);
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/grab", method = RequestMethod.POST)
	public void grab(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("loanId") int loanId,@RequestParam("sharedType") int sharedType) throws IllegalArgumentException, IllegalAccessException, ErrorException {
		
		CreditUserInfo userInfo = CreditServletContext.getUserInfo();
		if(userInfo.getIdentifyCheck().intValue()!=CodeValueUtil.IDENTIFY_CHECK.intValue()){
			throw new ErrorException(Constants.IDENTIFY_NOTCHECK_ERROR_CODE, Constants.IDENTIFY_NOTCHECK_ERROR_DESC);
		}
		
		CreditLoanOrder loanOrder = creditOrderService.findOrderById(loanId);
		
		Integer price = CalcuationOrderPriceUtil.calcuationPrice(loanOrder);
		
		if(sharedType == 1){//独享价格2倍
			price = price*2;
		}
		
		if(loanOrder.getOrderType().intValue() == CodeValueUtil.ORDERTYPE_EXCLUSIVE.intValue()){//专属单
			if(userInfo.getId()!=loanOrder.getCreditManager()){
				throw new ErrorException(Constants.COIN_NOTENOUGH_ERROR_CODE, Constants.COIN_NOTENOUGH_ERROR_DESC);
			}
		}
		
		if(userInfo.getCoin().intValue()<price.intValue()){//金币不足
			throw new ErrorException(Constants.COIN_NOTENOUGH_ERROR_CODE, Constants.COIN_NOTENOUGH_ERROR_DESC);
		}
		
		List<CreditGrabOrder> grabOrderList = creditGrabOrderService.findByManagerIdAndLoanId(userInfo.getId(),Long.valueOf(loanId));
		if(grabOrderList!=null&&grabOrderList.size()>0){
			throw new ErrorException(Constants.GRABORDER_REPEAT_ERROR_CODE, Constants.GRABORDER_REPEAT_ERROR_DESC);
		}
		
		CreditGrabOrder grabOrder2 = creditGrabOrderService.findByManagerIdAndLoanId(userInfo.getId(),Long.valueOf(loanId),CodeValueUtil.PROCESSFLAG_ABANDON);
		if(grabOrder2!=null){
			throw new ErrorException(Constants.GRABORDER_REPEAT_ERROR_CODE, Constants.GRABORDER_REPEAT_ERROR_DESC);
		}
		
		userInfo.setCoin(userInfo.getCoin()-price);
		userInfo.setScore(userInfo.getScore()+5); //抢单成功+5积分
		userService.updateUserInfo(userInfo);
		//添加金币消耗日志
		CoinUtil.addCoinRecord("2", userInfo.getId(), price, "抢单成功:消耗"+price+"枚金币",new BigDecimal(price));
		
		//发单表
		CreditGrabOrder grabOrder = new CreditGrabOrder();
		grabOrder.setAmount(loanOrder.getAmount());
		grabOrder.setCreateTime(loanOrder.getCreateTime());
		grabOrder.setCurrentCity(loanOrder.getCurrentCity());
		grabOrder.setDeadline(loanOrder.getDeadline());
		grabOrder.setProcessFlag(CodeValueUtil.PROCESSFLAG_TAKING);
		grabOrder.setProcessStatus(1);
		grabOrder.setLoanId(loanOrder.getId());
		grabOrder.setManagerId(userInfo.getId());
		grabOrder.setCreditUser(loanOrder.getUserId());
		grabOrder.setOrderType(loanOrder.getOrderType());
		grabOrder.setRealName(loanOrder.getRealName());
		grabOrder.setUpdateTime(new Date());
		String position = PositionUtil.getPosition(loanOrder);
		grabOrder.setPosition(position);
		
		creditGrabOrderService.addGrabOrder(grabOrder);
		
		if(sharedType == 1){ //修改状态，接单成功，订单结束
			loanOrder.setProcessFlag(CodeValueUtil.PROCESSFLAG_TAKING);
			loanOrder.setProcessStatus(1);
			loanOrder.setStatus(CodeValueUtil.STATUS_FINSHORDER);
		}else{
			if(loanOrder.getOrderType().intValue() == CodeValueUtil.ORDERTYPE_EXCLUSIVE.intValue()){
				loanOrder.setStatus(CodeValueUtil.STATUS_FINSHORDER);
				loanOrder.setProcessFlag(CodeValueUtil.PROCESSFLAG_TAKING);
				loanOrder.setProcessStatus(1);
			}else{
				if(loanOrder.getTakingPeople()>=4){//共享单人数为5修改状态，接单成功，订单结束
					loanOrder.setProcessFlag(CodeValueUtil.PROCESSFLAG_TAKING);
					loanOrder.setProcessStatus(1);
					loanOrder.setStatus(CodeValueUtil.STATUS_FINSHORDER);
				}else{
					loanOrder.setStatus(CodeValueUtil.STATUS_PEOPLETAKE);
				}
			}
		}
		loanOrder.setSharedType(sharedType);
		loanOrder.setTakingPeople(loanOrder.getTakingPeople()+1); //人数+1
		creditOrderService.updateLoanOrder(loanOrder);
		
		//final int number = price;
		
		//单子日志,信贷经理日志，用户日志
		LoanLogUtil.addLoanLog(Long.valueOf(loanId), userInfo.getId(), "抢单成功:消耗"+price+"枚金币", loanOrder.getProcessFlag(),loanOrder.getProcessStatus(),1);//经理日志
		
		CreditLoanLog creditLoanLog = creditLoanLogService.findLoanLogByLoanIdAndUid(Long.valueOf(loanId), loanOrder.getUserId(),CodeValueUtil.PROCESSFLAG_TAKING,1,2);//用户日志
		if(creditLoanLog!=null){
			creditLoanLog.setDescrible(loanOrder.getTakingPeople()+"位经理已接单，经理会马上联系您");
			creditLoanLogService.updateLoanLog(creditLoanLog);
		}else{
			LoanLogUtil.addLoanLog(Long.valueOf(loanId), loanOrder.getUserId(), loanOrder.getTakingPeople()+"位经理已接单，经理会马上联系您", loanOrder.getProcessFlag(),loanOrder.getProcessStatus(),2);//用户日志
		}
		
	}
	
	
	/**
	 * 获取信贷订单列表
	 * @param request
	 * @param response
	 * @param creditType
	 * @param pageNumber
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	@ResponseBody
	@RequestMapping(value = "/succCase", method = RequestMethod.POST)
	public void succCase(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "page", defaultValue = "1") int pageNumber) throws IllegalArgumentException, IllegalAccessException{
		CreditUserInfo userInfo = CreditServletContext.getUserInfo();
		
		Map<String, Object> searchParams = new TreeMap<String, Object>();
		
		//searchParams.put("IN_status",new Integer[]{CodeValueUtil.STATUS_TAKINGORDER,CodeValueUtil.STATUS_CANCELORDER,CodeValueUtil.STATUS_FINSHORDER});
		searchParams.put("EQ_processFlag", CodeValueUtil.PROCESSFLAG_LOAN);
		searchParams.put("EQ_processStatus", 1);
		Map<String, SearchDataTransform> dataTyps = new HashMap<String, SearchDataTransform>();
		

		Page<CreditLoanOrder> page = creditOrderService.getListPage(searchParams, pageNumber, ParamsConstant.PAGESIZE, "createTime", dataTyps);
		
		List<CreditLoanOrder> orderList = page.getContent();
		List<String> caseList = new ArrayList<String>();
		for(CreditLoanOrder loanOrder:orderList){
			//orderListReturn.add(BeanToMapUtil.getMap(loadOrder));
			//CreditUserInfo borrower = userService.findUserById(loanOrder.getUserId());
			CreditUserInfo manager = userService.findUserById(loanOrder.getCreditManager());
			String tip = RealNameUtil.getAppellation(loanOrder.getRealName(), loanOrder.getSex())+"通过平台"+manager.getRealName().substring(0, 1)+"经理已贷款"+AmountUtil.getAmountDesc(loanOrder.getAmount());
			caseList.add(tip);
		}
		
		ResBean resBean = CreditServletContext.getResBean();
		resBean.getData().put("caseList", caseList);
		CreditServletContext.setResBean(resBean);
	}
	
	
	/**
	 * 获取信贷订单列表
	 * @param request
	 * @param response
	 * @param creditType
	 * @param pageNumber
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	@ResponseBody
	@RequestMapping(value = "/pushOrderList", method = RequestMethod.POST)
	public void pushOrderList(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "page", defaultValue = "1") int pageNumber) throws IllegalArgumentException, IllegalAccessException{
		CreditUserInfo userInfo = CreditServletContext.getUserInfo();
		
		Set<Object> set = redisService.getForZSet(ParamsConstant.CREDIT_ORDER_PUSH_MESSAGE, String.valueOf(userInfo.getId()), pageNumber, true);
		
		Long[] ids = new Long[set.size()];
		int i = 0;
		for(Object object:set){
			ids[i] = (Long) object;
			i++;
		}
		
		List<Map<String,Object>> orderListReturn = new ArrayList<Map<String,Object>>();
		
        if(ids.length>0){
    		Map<String, Object> searchParams = new TreeMap<String, Object>();

    		searchParams.put("IN_id",ids);
    		Map<String, SearchDataTransform> dataTyps = new HashMap<String, SearchDataTransform>();
    		Page<CreditLoanOrder> page = creditOrderService.getListPage(searchParams, pageNumber, ParamsConstant.PAGESIZE, "createTime", dataTyps);
    		
    		List<CreditLoanOrder> orderList = page.getContent();
    		for(CreditLoanOrder loanOrder:orderList){
    			
    			Map<String,Object> paramsMap = ParamsMapUtil.replace(BeanToMapUtil.getMap(loanOrder));
    		/*	Integer sharePrice = CalcuationOrderPriceUtil.calcuationPrice(loadOrder);
    			paramsMap.put("sharePrice", sharePrice);//共享价格
    			paramsMap.put("exclusivePrice", 2*sharePrice);//独享价格
    			orderListReturn.add(paramsMap);*/
    			ParamsMapUtil.replace(paramsMap);
    			
    			Integer sharePrice = CalcuationOrderPriceUtil.calcuationPrice(loanOrder);
    			paramsMap.put("relativeTime", DateFormatUtil.format(loanOrder.getCreateTime()));//展示相对时间
    			paramsMap.put("workInfo", loanOrder.getCurrentCity()+" "+PositionUtil.getPosition(loanOrder)+PositionUtil.getStudentGrade(loanOrder));
    			paramsMap.put("creditInfo",PositionUtil.getCreditInfo(loanOrder));
    			paramsMap.put("sharePrice", sharePrice);//共享价格
    			paramsMap.put("exclusivePrice", 2*sharePrice);//独享价格
    			
    			//身份证
    			paramsMap.put("realName", RealNameUtil.getAppellation(loanOrder.getRealName(), loanOrder.getSex()));
    			if(loanOrder.getProcessFlag().intValue()<CodeValueUtil.PROCESSFLAG_TAKING){
    				paramsMap.put("IDNumber",!StringUtils.isEmpty(loanOrder.getIDNumber())?ParamsMapUtil.getIDNumber(loanOrder.getIDNumber()):"");
    				paramsMap.put("mobile", "");
    				//修改单位名称
    				ParamsMapUtil.updateCompanyName(paramsMap);
    			}else{
    				CreditUserInfo user = userService.findUserById(loanOrder.getUserId());
    				paramsMap.put("mobile", user.getMobile());
    			}
    		
    		}
        }
		
		ResBean resBean = CreditServletContext.getResBean();
		resBean.getData().put("orderList", orderListReturn);
		CreditServletContext.setResBean(resBean);
	}
	
	/**
	 * 标记审核订单接口
	 * @param request
	 * @param response
	 * @param creditType
	 * @param pageNumber
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	@ResponseBody
	@RequestMapping(value = "/checkOrder", method = RequestMethod.POST)
	public void checkOrder(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("loanId") long loanId,@RequestParam("checkStatus") int checkStatus) throws IllegalArgumentException, IllegalAccessException{
		
		creditOrderService.checkOrder(loanId,CodeValueUtil.PROCESSFLAG_CHECK,checkStatus);		
		
	}
	
	/**
	 * 订单放款接口
	 * @param request
	 * @param response
	 * @param creditType
	 * @param pageNumber
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws ErrorException 
	 */
	@ResponseBody
	@RequestMapping(value = "/loan", method = RequestMethod.POST)
	public void loan(HttpServletRequest request, HttpServletResponse response) throws  ErrorException{
		
			String loanId = request.getParameter("loanId");
			String loanStatus = request.getParameter("loanStatus");
			String loanImg = request.getParameter("loanImg");
			
			if(StringUtils.isEmpty(loanId)){
				throw new ErrorException(Constants.LOANID_NOTNULL_ERROR_CODE, Constants.LOANID_NOTNULL_ERROR_DESC);
			}
			
			if(StringUtils.isEmpty(loanStatus)){
				throw new ErrorException(Constants.LOANSTATUS_NOTNULL_ERROR_CODE, Constants.LOANSTATUS_NOTNULL_ERROR_DESC);
			}
			
			creditOrderService.loan(Long.valueOf(loanId),CodeValueUtil.PROCESSFLAG_LOAN,Integer.valueOf(loanStatus),loanImg);
		
	}
	
	/**
	 * 放弃
	 * @param request
	 * @param response
	 * @param creditType
	 * @param pageNumber
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws ErrorException 
	 */
	@ResponseBody
	@RequestMapping(value = "/abandon", method = RequestMethod.POST)
	public void abandon(HttpServletRequest request, HttpServletResponse response) throws  ErrorException{
		
			String loanId = request.getParameter("loanId");

			
			if(StringUtils.isEmpty(loanId)){
				throw new ErrorException(Constants.LOANID_NOTNULL_ERROR_CODE, Constants.LOANID_NOTNULL_ERROR_DESC);
			}
			

			
			creditOrderService.abandon(Long.valueOf(loanId));
		
	}
	
	/**
	 * 我的贷款详情接口(用户端)
	 * @param request
	 * @param response
	 * @param loanId
	 * @throws ErrorException
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	@ResponseBody
	@RequestMapping(value = "/detail", method = RequestMethod.POST)
	public void detail(HttpServletRequest request, HttpServletResponse response,@RequestParam("loanId") int loanId) throws  ErrorException, IllegalArgumentException, IllegalAccessException{
		
			CreditLoanOrder loanOrder = creditOrderService.findOrderById(loanId);
		
			if(loanOrder == null){
				throw new ErrorException(Constants.CREDITORDER_NOTEXISTS_ERROR_CODE, Constants.CREDITORDER_NOTEXISTS_ERROR_DESC);
			}
			
			List<CreditLoanLog> loanLogList = creditLoanLogService.findLoanLogByLoanIdAndUid(Long.valueOf(loanId), loanOrder.getUserId(),ParamsConstant.appTypeMap.get(request.getHeader("appName")));
	
			Map<String,Object> returnMap = BeanToMapUtil.getMap(loanOrder);
			
			List<Map<String,Object>> returnLogList = BeanToMapUtil.getList(loanLogList);
			
			returnMap.put("loanLogList", returnLogList);
			
			returnMap = ParamsMapUtil.replace(returnMap);
			
			ResBean resBean = CreditServletContext.getResBean();
			resBean.getData().put("loanOrder", returnMap);
			CreditServletContext.setResBean(resBean);
	}
	
	/**
	 * 我的贷款详情接口(经理端)
	 * @param request
	 * @param response
	 * @param loanId
	 * @throws ErrorException
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	@ResponseBody
	@RequestMapping(value = "/orderDetail", method = RequestMethod.POST)
	public void orderDetail(HttpServletRequest request, HttpServletResponse response,@RequestParam("loanId") int loanId) throws  ErrorException, IllegalArgumentException, IllegalAccessException{
		    CreditUserInfo userInfo = CreditServletContext.getUserInfo();
		
			CreditLoanOrder loanOrder = creditOrderService.findOrderById(loanId);
		
			if(loanOrder == null){
				throw new ErrorException(Constants.CREDITORDER_NOTEXISTS_ERROR_CODE, Constants.CREDITORDER_NOTEXISTS_ERROR_DESC);
			}
			
			List<CreditLoanLog> loanLogList = creditLoanLogService.findLoanLogByLoanIdAndUid(Long.valueOf(loanId), userInfo.getId(),ParamsConstant.appTypeMap.get(request.getHeader("appName")));
			
			
			//抢单信息
			List<CreditGrabOrder> grabOrderList = creditGrabOrderService.findByManagerIdAndLoanId(userInfo.getId(),loanOrder.getId());
			CreditGrabOrder creditGrabOrder = null;
			if(grabOrderList!=null&&grabOrderList.size()>0){
				creditGrabOrder = grabOrderList.get(0);
			}
			
			
			Map<String,Object> returnMap = BeanToMapUtil.getMap(loanOrder);
			
			List<Map<String,Object>> returnLogList = BeanToMapUtil.getList(loanLogList);
			
			returnMap.put("invest", returnLogList);
			
			returnMap = ParamsMapUtil.replace(returnMap);
			
			Integer sharePrice = CalcuationOrderPriceUtil.calcuationPrice(loanOrder);
			returnMap.put("sharePrice", sharePrice);//共享价格
			returnMap.put("exclusivePrice", 2*sharePrice);//独享价格

			if(creditGrabOrder!=null&&creditGrabOrder.getProcessFlag().intValue()>=CodeValueUtil.PROCESSFLAG_TAKING){
				CreditUserInfo user = userService.findUserById(loanOrder.getUserId());
				returnMap.put("mobile", user.getMobile());
			}else{
				//身份证
				returnMap.put("realName", RealNameUtil.getAppellation(loanOrder.getRealName(), loanOrder.getSex()));
				returnMap.put("IDNumber",!StringUtils.isEmpty(loanOrder.getIDNumber())?ParamsMapUtil.getIDNumber(loanOrder.getIDNumber()):"");
				returnMap.put("mobile", "");
				//修改单位名称
				ParamsMapUtil.updateCompanyName(returnMap);
			}
			
			returnMap.put("surplusCoins", userInfo.getCoin());
			
			Map<String,Object> grabOrderReturnMap = new HashMap<>();
			if(grabOrderList!=null&&grabOrderList.size()>0){
				grabOrderReturnMap = BeanToMapUtil.getMap(grabOrderList.get(0));
				ParamsMapUtil.replace(grabOrderReturnMap);
			}

			
			ResBean resBean = CreditServletContext.getResBean();
			resBean.getData().put("loanOrder", returnMap);
			resBean.getData().put("grabOrder", grabOrderReturnMap);
			CreditServletContext.setResBean(resBean);
	}

}
